﻿using System;
using System.Linq;
using System.Threading;
using System.Web;
using WSS.BLL.Resource;
using WSS.Models.Res;
using WSS.Pub;

namespace WSS.Web.Resource
{
    // <summary>
    // UploadHandle 的摘要说明
    // </summary>
    public class UploadHandle : IHttpHandler
    {

        private string UPLOADIFY_SAVETO { get; set; }

        private string _get_upload_saveto()
        {
            string upload_saveto;

            var appsettings = System.Configuration.ConfigurationManager.AppSettings.AllKeys;

            if (appsettings.Contains("Uploadify_SaveTo"))
            {
                UPLOADIFY_SAVETO = System.Configuration.ConfigurationManager.AppSettings["Uploadify_SaveTo"];

                upload_saveto = UPLOADIFY_SAVETO;

                upload_saveto = System.Web.HttpContext.Current.Server.MapPath(upload_saveto);

                if (!System.IO.Directory.Exists(upload_saveto))
                {
                    System.IO.Directory.CreateDirectory(upload_saveto);
                }
            }
            else
            {
                throw new Exception("web.config 文件 appsetting 节点未配置 Uploadify_SaveTo ");
            }

            return upload_saveto;
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";

            HttpPostedFile file = context.Request.Files["Filedata"];
            string upload_path = _get_upload_saveto() + "/" + context.Request["folder"];

            if (file != null)
            {

                if (!System.IO.Directory.Exists(upload_path))
                {
                    System.IO.Directory.CreateDirectory(upload_path);
                }

                string filename = System.IO.Path.GetFileName(file.FileName);
                //带空格的文件名转换时，会转换失败
                filename = filename.Replace(" ", "").Replace("　", "");

                string physical_path = upload_path + "/" + filename;

                file.SaveAs(physical_path);

                string extension_name = System.IO.Path.GetExtension(file.FileName).ToUpper();

                #region 上传完毕后，保存资源信息到数据库中

                RES_RESOURCE model = new RES_RESOURCE();

                model.CATE_NO = context.Request["cateno"];
                model.CATE_NO = model.CATE_NO.IsNullOrEmpty() ? "NONE" : model.CATE_NO;
                model.ORDER_NO = 1000;
                model.ORIG_FILE_LEN = file.ContentLength.ToString();
                model.ORIG_FILE_NAME = filename;

                string appconfig_saveto = UPLOADIFY_SAVETO;
                model.ORIG_PATH = appconfig_saveto + "/" + context.Request["folder"] + "/" + filename;
                model.RES_DESCRIPTION = "NONE";
                model.UPLOADER = context.Request["uploader"];
                model.UPLOAD_TIME = DateTime.Now;

                model.RES_FILE_LEN = "0";
                model.RES_FILE_NAME = "NONE";
                model.RES_NAME = filename.ToUpper().Replace(extension_name, "");
                model.RES_NO = DateTime.Now.ToString("yyyyMMddHHmmssfff");

                model.RES_PATH = "NONE";
                model.FLAG_DOWNLOAD = model.FALG_COMMENT = model.FLAG_PUBLIC = "Y";
                model.TOTAL_DOWNLOAD = model.TOTAL_COMMENT = model.TOTAL_READ = 0;
                model.CONVERTED_FILE_NAME = extension_name == ".PDF" ? model.ORIG_PATH : "NONE";

                WSS.BLL.Resource.ResDb.Instance.Insert(model);

                #endregion

                BaseRes base_res = new BaseRes
                {
                    MODEL_RES_RESOURCE = model,
                    MainHttpContext = context
                };

                _deal_convert_file(base_res, extension_name);

                context.Response.Write("1");
            }
            else
            {
                context.Response.Write("0");
            }
        }

        private void _deal_convert_file(BaseRes base_res, string extension_name)
        {
            if (extension_name == ".PDF")
            {
                base_res.ResourceCate = EResourceCategory.Pdf;
            }
            else if (extension_name == ".DOC" || extension_name == ".DOCX")
            {
                base_res.ResourceCate = EResourceCategory.Word;
            }
            else
            {
                return;
            }

            //FileConversionThread t = new FileConversionThread(base_res);

            ThreadStart thread_start = delegate()
            {
                new FileConversionThread(base_res);
            };
            Thread thread = new Thread(thread_start);
            thread.Start();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}